package com.bluezone.dec.uac;


import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.exception.TokenInvalidException;
import com.bluezone.dec.configuration.AppConfig;
import com.bluezone.dec.system.service.UserService;
import com.c503.sc.utils.response.ResultMessage;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import sc.c503.authclient.model.ApiUserEntity;
import sc.c503.authclient.service.splitImpl.ApiUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Class title: 权限验证拦截器
 * Describe: <br/>
 * Date : 2018/6/6 16:25 <br/>
 * Project : bluezone-zhyy-nav <br/>
 *
 * @author konbluesky
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    AppConfig appConfig;//设置一些key，过期时间等（devModel，keyName，expired）

    @Autowired
    UserService userService;

    /**
     * 在执行目标方法之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // uac 开启验证
        if (!appConfig.getUacStatus()) {
            return true;
        }
        //本身的系统header中获取token
        String token = request.getHeader(appConfig.keyName());

        if (token == null) {
            //从 requestParam中获取token
            token = request.getParameter(appConfig.keyName());
        }
        // 从uac验证
        ApiUserService us = UACServiceFactory.apiUserService(token);
        ResultMessage message = us.authToken();
        if (message.getCode() == 0) {
            JSONObject userInfo = userService.getUserInfo();
            if (userInfo == null) {
                ApiUserEntity user = us.getUserInfo();
                userService.saveUserInfo(user);
            }
            // 权限验证
            Preconditions.checkState(userService.authPermission(handler), "权限不足！");
            return userService.authPermission(handler);
        } else {
            throw new TokenInvalidException();
        }
    }

    /**
     * 执行目标方法之后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        log.info("拦截器postHandle");
    }

    /**
     * 在请求已经返回之后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {
        log.info("拦截器afterCompletion");
    }
}
